﻿package com.pandemicode.framework.input {
    import flash.display.Stage;
    import flash.events.Event;
	import flash.events.EventDispatcher;
    import flash.events.KeyboardEvent;
	import org.osflash.signals.natives.NativeSignal;

    /**
     * The Key class recreates functionality of
     * Key.isDown of ActionScript 1 and 2. Before using
     * Key.isDown, you first need to initialize the
     * Key class with a reference to the stage using
     * its Key.initialize() method. For key
     * codes use the flash.ui.Keyboard class.
     *
	 * @example
	 * <pre>
		 Key.initialize(stage);
		 if (Key.isDown(Keyboard.LEFT)) {
			// Left key is being pressed
		 }
	 * </pre>
     */
    public class Key {
        private static var _initialized:Boolean = false;  // marks whether or not the class has been initialized
        private static var _keysDown:Object = new Object();  // stores key codes of all keys pressed
		
		private static var _keyDown:NativeSignal;
		private static var _keyUp:NativeSignal;
		private static var _deactivated:NativeSignal;

        /**
         * Initializes the key class creating assigning event
         * handlers to capture necessary key events from the stage
         */
        public static function initialize(stage:Stage):void {
            if (!_initialized) {
                // assign listeners for key presses and deactivation of the player
				addListener(stage);

                // mark initialization as true so redundant
                // calls do not reassign the event handlers
                _initialized = true;
            }
        }
		
		/**
		 * Adds a listener to an EventDispatcher.
		 * @param	e	The EventDispatcher to add the listeners to.
		 */
		public static function addListener(e:EventDispatcher):void {
			_keyDown = new NativeSignal(e, KeyboardEvent.KEY_DOWN, KeyboardEvent);
			_keyUp = new NativeSignal(e, KeyboardEvent.KEY_UP, KeyboardEvent);
			_deactivated = new NativeSignal(e, Event.DEACTIVATE, Event);
			
			_keyDown.add(_keyPressed);
			_keyUp.add(_keyReleased);
			_deactivated.add(_clearKeys);
		}

        /**
         * Returns true or false if the key represented by the
         * @param	keyCode		The keyCode that is being pressed
         */
        public static function isDown(keyCode:uint):Boolean {
            if (!_initialized) {
                // throw an error if isDown is used
                // prior to Key class initialization
                throw new Error("Key class has yet been initialized.");
            }
            return Boolean(keyCode in _keysDown);
        }

        /**
         * Event handler for capturing keys being pressed
         */
        private static function _keyPressed(event:KeyboardEvent):void {
            // create a property in keysDown with the name of the keyCode
            _keysDown[event.keyCode] = true;
        }

        /**
         * Event handler for capturing keys being released
         */
        private static function _keyReleased(event:KeyboardEvent):void {
            if (event.keyCode in _keysDown) {
                // delete the property in keysDown if it exists
                delete _keysDown[event.keyCode];
            }
        }

        /**
         * Event handler for Flash Player deactivation
         */
        private static function _clearKeys(event:Event):void {
            // clear all keys in keysDown since the player cannot
            // detect keys being pressed or released when not focused
            _keysDown = new Object();
        }
    }
}